import { Modal, Button, Form, InputNumber, Select, message,Row,Col, Table} from 'antd';
import { connect } from 'dva';
import styles from './index.less';
import InputPrices from '@/components/plugins/InputPrices'

const FormItem = Form.Item;
const Option = Select.Option;
function hasErrors(fieldsError) {
    let error = Object.keys(fieldsError).some(field => fieldsError[field]);
    return error;
}

@Form.create()
class ChangePrice extends React.Component {

    constructor(props) {
        super(props);
        this.state= {
            columns: [],
            btnLoading: false
        }
    }

    componentWillMount() {
        window.Isoption = false;
      }
      componentDidMount() {
        window.Isoption = true;
      }

    handleOk = () => {
        const { _thisInSale, _thisInStock,_thisSoldOut } = this.props;
        const _this = _thisInSale|| _thisInStock||_thisSoldOut;
        _this.setState({ editPriceVisible: false }, () => {
            this.forceUpdate();
        });
    };

    handleCancel = () => {
        const { _thisInSale, _thisInStock,_thisSoldOut } = this.props;
        const _this = _thisInSale|| _thisInStock||_thisSoldOut;
        _this.setState({ editPriceVisible: false }, () => {
            this.forceUpdate();
        });
    };

    // 取消
    clickCancel =() => {
        this.setState({
            allValue: '',
        })
        this.handleCancel();
    }

    // 确认
    changePriceBtn =() => {
        this.props.form.validateFields((err, values) => {
            if(!err) {
                const { _thisInSale, _thisInStock,_thisSoldOut, dispatch, ProductId, sourceDatas} = this.props;
                const ProductSku = [];
                this.setState({
                    btnLoading: true
                })
                sourceDatas.map((item, index) => {
                    ProductSku.push({
                        SkuId: item.skuId,
                        SalePrice: item.price
                    })
                    return ProductSku;
                })
                dispatch({
                    type: 'pruductSellList/UpdateSProductPrice',
                    payload: {
                        ProductId: ProductId,
                        ProductSku: ProductSku
                    },
                    callBack: {
                        success: res => {
                          if (res.Code === 0) {
                            message.success('修改成功');
                            this.handleOk();
                            if(_thisInSale) {
                                this.props._thisInSale.GetSellProductList();
                            }
                            if(_thisInStock) {
                                this.props._thisInStock.getSearchWarehouseProductListWithPage();
                            }
                            if(_thisSoldOut) {
                                this.props._thisSoldOut.getSearchSoldOutProductListWithPage();
                            }
                            this.setState({
                                allValue: '',
                                btnLoading: false
                            })
                          }
                        },
                        error: res => {
                          message.error(res.Msg);
                          this.setState({ btnLoading: false });
                        },
                    },
                })
            }    
        }) 
    }

    getAllInputValue =(value, data) => {
        this.setState({
            allValue: value,
        })
    }

    getInputValue =(e, value, data, index) => {
        const {dispatch, sourceDatas} = this.props;
        sourceDatas[index].price = e;
        dispatch({
            type:'pruductSellList/changeData',
            payload:sourceDatas,
            callBack:{
                success:(res)=>{
                    this.forceUpdate();
                }
            }
        })
  }

    // 保存
    clickSetOnTime =() => {
        this.props.form.validateFields((error) => {
            if(!error) {
                const { allValue} = this.state;
                const {sourceDatas,dispatch} = this.props;
                sourceDatas.map((item, index) => {
                    item.price = allValue;
                })
                dispatch({
                    type:'pruductSellList/changeData',
                    payload:sourceDatas,
                    callBack:{
                        success:(res)=>{
                            this.forceUpdate();
                        }
                    }
                })
            }
        })
    }

    checkBlur = (id) => {
        this.props.form.validateFields([id], { force: true });
      }

    render() {
        const {editPriceVisible, productSkuInfo, skuId, ProductId,sourceDatas} = this.props;
        const {getFieldDecorator} = this.props.form;
        const {btnLoading} = this.state;
        const formItemLayout = {
            labelCol: {
              span: 4 ,
            },
            wrapperCol: {
              span: 8 ,
            },
          };

          /****/
          // const {sourceDatas} = this.props;
          const data = sourceDatas;
          let skuList=[];
          let rex1=/^k[0-9]*$/gi;
          if (data&&data.length> 0) {
              Object.keys(data[0]).forEach(function(key){
                  if(key.match(rex1))
                  {
                      var sid=key.replace("k","");
                      let item={ id:data[0]["k"+sid+"_id"],name:data[0][key] };
                      skuList.push(item);
                  }
             });
          }
          skuList.push(
              { id:0, name:'价格' }
          );

          let arr = [], obj = {};

          let g1=0;
          let g2=0;
          let g3=0;
          const columns = [];
          skuList.forEach((item,itemIndex)=>{
              let dataIndex="v1";
              let width = 0;
              let align = '';
              if (skuList.length=== 4) {
                  if(itemIndex===0) {
                      dataIndex="v1";
                      width = '25%';                     
                  }
                  if(itemIndex===1){
                      dataIndex="v2";
                      width = '25%';
                  }
                   if(itemIndex===2){
                      dataIndex="v3";
                      width = '25%';
                  }
                  if (itemIndex===3){
                      dataIndex="price";
                      width = 120;
                  }
               } if (skuList.length=== 3) {
                  if(itemIndex===0) {
                      dataIndex="v1";
                      width = '35%';
                  }
                  if(itemIndex===1){
                      dataIndex="v2";
                      width = '35%';
                  }
                  if (itemIndex===2){
                      dataIndex="price";
                      width = '30%';
                  }
               } if (skuList.length=== 2) {
                if(itemIndex===0) {
                    dataIndex="v1";
                    width = '40%';
                }
                 if (itemIndex===1){
                    dataIndex="price";
                    width = '20%';
                }
               }

              let col={
                  title: item.name,
                  dataIndex: dataIndex,
                  width:  width,
                  align: 'left',
                  render: (text, row, index) => {
                    const obj = {
                        children: text,
                        props: {},
                        };
                    if (skuList.length=== 4) {
                      if(itemIndex===0){
                          if(row.v1_id!==g1){
                              obj.props.rowSpan = row.row_1_num;
                              g1=row.v1_id;
                              g2=0;
                              g3=0;
                          }
                          else{
                              obj.props.rowSpan=0;
                          }
                       }
                       if(itemIndex===1) {
                          if(row.v2_id!==g2){
                              obj.props.rowSpan = row.row_2_num;
                              g2=row.v2_id;
                              g3=0;
                          }else{
                              obj.props.rowSpan=0;
                          }
                       }
                       if(itemIndex===2) {
                          if(row.v3_id!==g3){
                              obj.props.rowSpan = row.row_3_num;
                              g3=row.v3_id;
                          }else{
                              obj.props.rowSpan=0;
                          }
                       }
                       if (itemIndex===3){
                          return (
                            <FormItem>
                                {this.props.form.getFieldDecorator('price' + index, {
                                    initialValue: data[index].price,
                                    rules: [
                                        {required: true,message: `请输入价格`},
                                        {pattern: /^0\.([1-9]|\d[1-9])$|^[1-9]\d{0,8}\.\d{0,2}$|^[1-9]\d{0,8}$/, message: '不小于0.01'}
                                    ]
                                 })(
                                    <InputPrices
                                        min={0}
                                        max={999999}
                                        style={{width: '100%'}}
                                        onChange={e => this.getInputValue(e,row,data,index)}
                                        setValue={data[index].price}
                                        onBlur={() => { this.checkBlur('price' + index) }}
                                    />                               
                                   ) 
                                }
                            </FormItem>      
                          )
                       }
                    } if (skuList.length=== 3) {
                      if(itemIndex===0){
                          if(row.v1_id!==g1){
                              obj.props.rowSpan = row.row_1_num;
                              g1=row.v1_id;
                              g2=0;
                              g3=0;
                          }
                          else{
                              obj.props.rowSpan=0;
                          }
                       }
                       if(itemIndex===1) {
                          if(row.v2_id!==g2){
                              obj.props.rowSpan = row.row_2_num;
                              g2=row.v2_id;
                              g3=0;
                          }else{
                              obj.props.rowSpan=0;
                          }
                       }
                        if (itemIndex===2){
                          return (
                            <FormItem>
                                {this.props.form.getFieldDecorator('price' + index, {
                                    initialValue: data[index].price,
                                    rules: [{
                                        required: true,
                                        message: `请输入价格`
                                    },
                                    {pattern: /^0\.([1-9]|\d[1-9])$|^[1-9]\d{0,8}\.\d{0,2}$|^[1-9]\d{0,8}$/, message: '不小于0.01'}
                                    ]
                                })(
                                        <InputPrices
                                            min={0}
                                            max={999999}
                                            style={{width: '100%'}}
                                            onChange={e => this.getInputValue(e,row,data,index)}
                                            setValue={data[index].price}
                                            onBlur={() => { this.checkBlur('price' + index) }}
                                        />                               
                                ) 
                                }
                            </FormItem>
                          )
                       }
                    } if (skuList.length=== 2) {
                        if(itemIndex===0){
                            if(row.v1_id!==g1){
                                obj.props.rowSpan = row.row_1_num;
                                g1=row.v1_id;
                            }
                            else{
                                obj.props.rowSpan=0;
                            }
                         }
                        if (itemIndex===1){
                            return (
                                <FormItem>
                                    {this.props.form.getFieldDecorator('price' + index, {
                                        initialValue: data[index].price,
                                        rules: [{
                                            required: true,
                                            message: `请输入价格`
                                        },
                                        {pattern: /^0\.([1-9]|\d[1-9])$|^[1-9]\d{0,8}\.\d{0,2}$|^[1-9]\d{0,8}$/, message: '不小于0.01'}
                                        ]
                                    })(
                                            <InputPrices
                                                min={0}
                                                max={999999}
                                                style={{width: '100%'}}
                                                onChange={e => this.getInputValue(e,row,data,index)}
                                                setValue={data[index].price}
                                                onBlur={() => { this.checkBlur('price' + index) }}
                                            />                               
                                    )}
                                </FormItem>
                            )
                         }
                    }
                    return obj;
                  },
              }
              columns.push(col)
          })

        return (
            <Form>
                <Modal
                    visible={editPriceVisible}
                    title="修改价格"
                    onOk={this.handleOk}
                    onCancel={this.handleCancel}
                    className={styles.form}
                    footer={null}
                    width={640}
                >
                    <div className={styles.modalTableContent}>
                        <Table
                            bordered
                            dataSource={sourceDatas}
                            pagination={false}
                            columns={columns}
                            rowKey ={(record) => record.id}
                            className={styles.tableBox}

                        />
                    </div>
                    <div className={styles.footerLine}>
                        <FormItem label="批量设置" {...formItemLayout}>
                            {getFieldDecorator('numbers', {
                                    rules: [
                                    {required: false, message: ''},
                                    {pattern: /^0\.([1-9]|\d[1-9])$|^[1-9]\d{0,8}\.\d{0,2}$|^[1-9]\d{0,8}$/, message: '不小于0.01'}
                                ]
                            })(
                                <span className={styles.inputBox}>
                                    <InputNumber
                                        placeholder="请填写价格"
                                        min={0} max={999999}
                                        value={this.state.allValue}
                                        onChange={e => this.getAllInputValue(e, sourceDatas)}
                                    />
                                    <a
                                    href="javascript:;"
                                    style={{width: '3em', marginLeft: 8}}
                                    onClick={() => this.clickSetOnTime()}>
                                        保存
                                    </a>
                                </span>
                            )}
                        </FormItem>
                        <div>
                            <Button onClick={this.clickCancel}>取消</Button>
                            <Button
                                type="primary"
                                style={{marginLeft: 8}}
                                onClick ={this.changePriceBtn}
                                loading={btnLoading}
                            >
                             确认
                          </Button>
                        </div>
                    </div>
                </Modal>
            </Form>
        )
    }
}

export default connect(({productSkuInfo,pruductSellList, global, loading}) => ({
    productSkuInfo,
    loading: loading.effects['pruductSellList/GetSellProductList'],
    sourceDatas:pruductSellList.sourceData
}))(ChangePrice)
